package com.kitty.game.utils.dirtywords;


import com.kitty.common.cache.RedisService;
import com.kitty.common.cache.service.AppPropertiesService;

import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class WordService {

    Set<String> words = new HashSet<>();
    private final Map<Character, List<String>> dirtyWords = new HashMap<>();
    @Autowired
    Dao dao;
    @Autowired
    RedisService redisService;
    @Autowired
    AppPropertiesService appPropertiesService;
    @PostConstruct
    private void init() {
        List<Word> list = dao.query(Word.class, Cnd.NEW());
        Set<String> set = new HashSet<>();
        for (Word word: list){
            set.add(word.getWord());
        }
        initWordsStore(set);
        log.error("初始化敏感词汇==={}", set.size());
    }


    public List<String> checkDirtyWords(String sentence) {
        char[] stringArr = sentence.toCharArray();
        int wordCount = stringArr.length;
        List<String> result = new ArrayList<>();
        for (int i = 0; i < wordCount - 1; i++) {
            char key = stringArr[i];
            if (dirtyWords.containsKey(key)) {
                int endIndex = Math.min(10, wordCount - i);
                String checkWord = new String(stringArr, i, endIndex);
                String matchedKey = checkWordsMatch(checkWord, key);
                if (matchedKey != null && matchedKey.trim().length() > 0) {
                    result.add(matchedKey);
                }
            }
        }
        return result;
    }

    private String checkWordsMatch(String source, Character key) {
        List<String> match = dirtyWords.get(key);
        for (String unit:match) {
            DirtyWordUnit wordUnit = new DirtyWordUnit(source,unit);
            wordUnit.checkWordIndex();
            if (wordUnit.foundDitryWord()) {
                return wordUnit.getKeyWord();
            }
        }
        return  "";
    }


    private void initWordsStore(Set<String> words) {
        for (String word : words) {
            char first = word.charAt(0);
            List<String> sameFirst = dirtyWords.computeIfAbsent(first, k -> new ArrayList<>());
            sameFirst.add(word);
        }
    }
}
